package amani.wechat.platform.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.req.model.message.IndustryTemplateMessageSend;
import org.jeewx.api.core.req.model.message.TemplateData;
import org.jeewx.api.core.req.model.message.TemplateMessage;
import org.jeewx.api.core.util.HttpRequestProxy;
import org.jeewx.api.coupon.consume.JwCardConsumeAPI;
import org.jeewx.api.wxsendmsg.JwTemplateMessageAPI;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import amani.wechat.platform.controller.model.ActivateCard;
import amani.wechat.platform.controller.model.AddCardReturnData;
import amani.wechat.platform.controller.model.CardComsumeReturnData;
import amani.wechat.platform.controller.model.NotifyReturnData;
import amani.wechat.platform.controller.model.Result;
import amani.wechat.platform.services.ICardConsumeService;
import amani.wechat.platform.services.ICommonService;
import amani.wechat.platform.utils.HttpRequestUtils;
import amani.wechat.platform.utils.WxUtils;

import com.tencent.common.Signature;
import com.tencent.common.XMLParser;

@Controller
public class CommonController {
	
	private static Logger logger = Logger.getLogger(OrdersController.class);
	@Resource(name="CommonService")
	ICommonService commonService ;
	
	@Resource(name="CardConsumeService")
	ICardConsumeService cardConsumeService ;
	
	/**
	 * 激活会员卡
	 * @param model
	 * @return
	 * @throws WexinReqException
	 */
	@RequestMapping("/card/active")
	public String cardActive( Model model,HttpSession session) throws WexinReqException{
		JSONObject obj=new JSONObject();
		String openid = session.getAttribute("openid").toString();
		//String cardno = (String)session.getAttribute("electronicCardNo");
		List<ActivateCard> alist = commonService.loadAccount(openid);
		ActivateCard a = new ActivateCard();
		for(ActivateCard t :alist){
			a = t;
			obj.put("membership_number",a.getMembership_number());
			obj.put("code",a.getCode());
			obj.put("card_id",a.getCard_id());
			obj.put("init_bonus",a.getInit_bonus());
			obj.put("init_balance",a.getInit_balance()*100);
			System.out.println(a.getMembership_number()+"|"+a.getCode()+"|"+a.getCard_id()+"|"+a.getInit_bonus()+"|"+a.getInit_balance()+"|\n"+WxUtils.GetAccessToken());
			String reqUrl=String.format(
					"https://api.weixin.qq.com/card/membercard/activate?access_token=%s",
					WxUtils.GetAccessToken()); 
			Map parameters=new HashMap();
			String jsonResultStr = HttpRequestProxy.doJsonPost(reqUrl, parameters, obj.toString());//(reqUrl, obj, "UTF-8");
			JSONObject jsonResult=JSONObject.fromObject(jsonResultStr);//.get("errmsg") 
			System.out.println(jsonResult.containsKey("errmsg")+"|"+jsonResult.getString("errmsg"));
			if(jsonResult.containsKey("errmsg")&& jsonResult.getString("errmsg").equals("ok")){
				model.addAttribute("activeState", "Successed");
			}
		}
		
		//组织激活参数
		  
		return "common/activeCard";
	}
	
	
	/**
	 * 导入code到微信
	 * @param cardId
	 * @param codes
	 * @return
	 * @throws WexinReqException
	 */
	@RequestMapping("/deposit")
	@ResponseBody
	public Result deposit(String cardId,String codes) throws WexinReqException{
		JSONObject obj=new JSONObject();
		//http://mp.weixin.qq.com/wiki/12/ccd3aa0bddfe5211aace864de00b42e0.html#.E5.AF.BC.E5.85.A5code.E6.8E.A5.E5.8F.A3
		//导入code
		obj.put("card_id", cardId);
		String[] cdoesStr=codes.split(",");
		net.sf.json.JSONArray codesArray=new  net.sf.json.JSONArray();
		for (int i = 0; i < cdoesStr.length; i++) {
			codesArray.add(cdoesStr[i]);
		}
		
		obj.put("code", codesArray);
		
		HttpRequestProxy proxy = new HttpRequestProxy();
		String reqUrl=String.format(
				"http://api.weixin.qq.com/card/code/deposit?access_token=%s",
				WxUtils.GetAccessToken()) ;
		String jsonResultStr = proxy.doPost(reqUrl, obj, "UTF-8");
		Result result =new Result();
		JSONObject jsonResult=JSONObject.fromObject(jsonResultStr);//.get("errmsg")
		result.setIsok(false);
		if(jsonResult.containsKey("errmsg")){
			result.setIsok(jsonResult.getString("errmsg").equals("ok"));
		} 
		return result; 
	}

	@RequestMapping("/WxRequest")
	@ResponseBody
	public void WxRequest(String signature, String timestamp, String nonce,
			String echostr, HttpServletResponse response) throws IOException {
		String token = "wangweiwei";
		Map<String, String> map = new TreeMap<String, String>();
		map.put("token", token);
		map.put("timestamp", timestamp);
		map.put("nonce", nonce);
		String[] values = { token, timestamp, nonce };
		Arrays.sort(values); // 字典序排序
		String value = values[0] + values[1] + values[2];
		String sign = DigestUtils.shaHex(value);
		PrintWriter writer = response.getWriter();
		if (sign.equals(signature)) {
			writer.print(echostr);
		} else {
			writer.print("error");
		}
		writer.flush();

		writer.close();
	}
	
	@RequestMapping("/SendCard") 
	@ResponseBody 
	public AddCardReturnData SendCard(String cardId,String cardCode,String orderNo,HttpServletRequest request) throws WexinReqException {
		AddCardReturnData result=new AddCardReturnData();
		result.setCardId(cardId); 
		String openid=(String)request.getSession().getAttribute("openid");
		if(cardCode==null){
			cardCode=commonService.getCardcode(cardId);
		}
		commonService.updtaeOrderCard(orderNo, cardId, cardCode);
		commonService.updtaeCardCodeState(cardCode, 1);
		result.setCardExt(WxUtils.getCardExt(cardId,cardCode, openid));  
		return result;
		
	}

	/**
	 * 微信支付成功之后通知
	 * 
	 * @param out_trade_no
	 *            订单编号
	 * @return
	 * @throws IOException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 * @throws WexinReqException
	 */
	@RequestMapping("Pay/Notify")
	@ResponseBody
	public NotifyReturnData PayNotify(HttpServletRequest request)
			throws IOException, ParserConfigurationException, SAXException,
			WexinReqException {
		NotifyReturnData returnData = new NotifyReturnData();
		String content = HttpRequestUtils.ReadRequestContent(request);
		Map<String, Object> map = XMLParser.getMapFromXML(content);
		logger.info(String.format("【接收到的notify通知】:%n%s%n", content));
		// 检查签名信息
		String sign = Signature.getSign(map);
		//if (map.get("sign").equals(sign)) {
			returnData.setReturn_code("SUCCESS");
			if (map.get("return_code").equals("FAIL")) {
				// 此处应该更新一下订单状态，商户自行增删操作【通信出错】
				logger.info(String.format("【通信出错】:%n%s%n", content));
			} else if (map.get("result_code").equals("FAIL")) {
				// 此处应该更新一下订单状态，商户自行增删操作【业务出错】
				logger.info(String.format("【业务出错】:%n%s%n", content));
			} else {
				logger.info(String.format("【支付成功】:%n%s%n", content));

				String orderId = (String) map.get("out_trade_no");// 订单id
				String openid = (String) map.get("openid");// 支付的用户ID
				Boolean needSendMessgae=false;
				if(orderId.startsWith("JJ-")){
					needSendMessgae=commonService.getOrderStateByOrderNo(orderId, "shop")==0;
				}else { 
					needSendMessgae=commonService.getOrderStateByOrderNo(orderId, "other")==0;
				}
				if(needSendMessgae){
					// 查询订单信息并更新订单状态 
					//向用户发送消费通知
					String accessToken = WxUtils.GetAccessToken();
					IndustryTemplateMessageSend industryTemplateMessageSend = new IndustryTemplateMessageSend();
					industryTemplateMessageSend.setAccess_token(accessToken);
					industryTemplateMessageSend
							.setTemplate_id("3Kj6mtZ8CmJY7S4XQ5kvu10wSlhtbV9X3ef6QAQlRms");// 暂时写死
					industryTemplateMessageSend.setTouser(openid);
					industryTemplateMessageSend.setUrl("");
					industryTemplateMessageSend.setTopcolor("#FF0000");
					TemplateMessage data = new TemplateMessage();
					TemplateData first = new TemplateData();
					first.setColor("#173177");
					first.setValue("您好，您已为订单："+orderId+"成功支付。");
					data.setFirst(first);
	
					String timeEnd=(String)map.get("time_end");
					
					TemplateData keynote1 = new TemplateData();
					keynote1.setColor("#173177");
					keynote1.setValue(timeEnd.substring(0,4)+"年"+timeEnd.substring(4,6)+"月"+timeEnd.substring(6,8)+"日"+" "+timeEnd.substring(8,10)+":"+timeEnd.substring(10,12)+":"+timeEnd.substring(12));
					data.setKeyword1(keynote1);
	
	
					String accountString=(String)map.get("cash_fee");
					TemplateData keynote2 = new TemplateData();
					keynote2.setColor("#173177");
					keynote2.setValue(((Double)(Double.parseDouble(accountString)/100)).toString()+"元");
					data.setKeyword2(keynote2); 
	
					TemplateData remark = new TemplateData();
					remark.setColor("#173177");
					remark.setValue("感谢您的支持，如有疑问，请拨打4006622818");
					data.setRemark(remark);
					industryTemplateMessageSend.setData(data); 
					JwTemplateMessageAPI.sendTemplateMsg(industryTemplateMessageSend);
					if(!orderId.startsWith("JJ-")){
						
		
						//向员工发送预约消息
						
						
						commonService.updtaeOrderStateByOrderNo(orderId, "other", 1);
					}else {
						//更新订单状态
						commonService.updtaeOrderStateByOrderNo(orderId, "shop", 1);
					}
				}

			}
//		} else {
//			returnData.setReturn_code("FAIL");
//			returnData.setReturn_msg("签名失败");
//		}
		return returnData;
	}

	/**
	 * 核销卡券接口
	 * 
	 * @param cardNo
	 * @param cardId
	 * @return
	 * @throws WexinReqException
	 */
	@RequestMapping("Card/Consume")
	@ResponseBody
	public String consumeCardNo(String cardNo, String cardId)
			throws WexinReqException {
		String accessToken = WxUtils.GetAccessToken();
		JSONObject obj=new JSONObject();
		obj.put("code",cardNo);
		obj.put("card_id",cardId);
		String reqUrl=String.format(
				"https://api.weixin.qq.com/card/code/consume?access_token=%s",
				WxUtils.GetAccessToken());
		Map parameters=new HashMap();
		String jsonResultStr = HttpRequestProxy.doJsonPost(reqUrl, parameters,obj.toString());
		return jsonResultStr;
	}
	@RequestMapping("index/noneOpenid")
	private String NoneOpenId() {
		// TODO Auto-generated method stub
		return "index/noneOpenId";
	}
	/**
	 * 微信消息和事件回掉
	 * @param request
	 * @throws IOException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 */
	@RequestMapping("index/wxapi")
	@ResponseBody
	public void wxapi(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ParserConfigurationException, SAXException {
		String content = HttpRequestUtils.ReadRequestContent(request); 
		PrintWriter writer = response.getWriter();
		boolean checkedSuccess=false;
		if(request.getParameter("signature")!=null && !request.getParameter("signature").equals("")){
			String token = WxUtils.getCheckToken();
			String signature=request.getParameter("signature");
			String timestamp=request.getParameter("timestamp");
			String nonce=request.getParameter("nonce");
			String echostr=request.getParameter("echostr");
			Map<String, String> map = new TreeMap<String, String>();
			map.put("token", token);
			map.put("timestamp", timestamp);
			map.put("nonce", nonce);
			String[] values = { token, timestamp, nonce };
			System.out.println(token+"|"+timestamp+"|"+nonce+"|"+values);
			Arrays.sort(values); // 字典序排序
			String value = values[0] + values[1] + values[2];
			String sign = DigestUtils.shaHex(value);
			
			if (sign.equals(signature)) {
				if(echostr==null){
					checkedSuccess=true;
				}else{
					writer.print(echostr);
				}
			} else {
				writer.print("error");
				writer.flush();

				writer.close(); 
				return;
			}
			
		}else{ 
			 checkedSuccess=true;
		}
		
		
		
		//String content = HttpRequestUtils.ReadRequestContent(request);

		if (!content.equals("") && checkedSuccess) {
			String responseString="";
			
			Map<String, Object> map = XMLParser.getMapFromXML(content);
			String fromUsername = (String) map.get("FromUserName");
			String toUsername = (String) map.get("ToUserName");
			String msgType = (String) map.get("MsgType");
			// String $time = time();
			String messageContentString="";
			switch (msgType) {
			case "text"://文本信息
				messageContentString=((String)map.get("Content")).trim();
				break;
			case "image"://图片信息

				break;
			case "voice":

				break;
			case "video":

				break;
			case "location":

				break;
			case "link":

				break;
			case "event":
				String eventString=(String)map.get("Event");
				switch (eventString) {
				case "subscribe"://订阅微信公众号处理
					
					break;
				case "CLICK":
					
					break;
				case "LOCATION":
					
					break;
				case "user_consume_card"://卡券核销通知
					cardConsumeService.Consume((String)map.get("UserCardCode"));
					break;

				default:
					break;
				}
				break;

			default:
				break;
			}
			if(!messageContentString.equals("")){
				if(messageContentString.startsWith("YGBD#")){//绑定员工信息
					if(commonService.bandStaffInfo(messageContentString+"#"+fromUsername)){
						responseString="<xml>"+
								"<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"+
								"<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"+
								"<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>"+
								"<MsgType><![CDATA[text]]></MsgType>"+
								"<Content><![CDATA[绑定成功，请输入#YGXX维护员工个人信息]]></Content>"+
								"</xml>";
					}else{
						responseString="<xml>"+
								"<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"+
								"<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"+
								"<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>"+
								"<MsgType><![CDATA[text]]></MsgType>"+
								"<Content><![CDATA[绑定失败]]></Content>"+
								"</xml>";
					}
				}else if(messageContentString.startsWith("#YGXX")){
					responseString="<xml>"+
							"<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"+
							"<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"+
							"<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>"+
							"<MsgType><![CDATA[news]]></MsgType>"+
							"<ArticleCount>2</ArticleCount>"+
							"<Articles>"+
							"<item>"+
							"<Title><![CDATA[员工信息]]></Title> "+
							"<Description><![CDATA[维护员工个人信息]]></Description>"+
							"<PicUrl><![CDATA[]]></PicUrl>"+
							"<Url><![CDATA["+WxUtils.getWebsiteRoot()+"/Staff/index"+"]]></Url>"+
							"</item>"+
							"<item>"+
							"<Title><![CDATA[作品上传]]></Title>"+
							"<Description><![CDATA[维护员工作品信息]]></Description>"+
							"<PicUrl><![CDATA[]]></PicUrl>"+
							"<Url><![CDATA["+WxUtils.getWebsiteRoot()+"/Staff/works"+"]]></Url>"+
							"</item>"+
							"</Articles>"+
							"</xml>";
				}else{
					responseString="<xml>"
							+ "<ToUserName><![CDATA["+fromUsername+"]]></ToUserName>"
							+ "<FromUserName><![CDATA["+toUsername+"]]></FromUserName>"
							+ "<CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>"
							+ "<MsgType><![CDATA[transfer_customer_service]]></MsgType>"
							+ "</xml>";
				}
			}
			if(!responseString.equals("")){
				writer.print(responseString);
				writer.flush(); 
				writer.close(); 
			}else {
				writer.print("success");
				writer.flush(); 
				writer.close(); 
			}
		} 

	}
	
	/**
	 * 系统服务验证码提醒
	 * @return
	 */
	@RequestMapping("ei/template")
	@ResponseBody
	public String Ssvcr(String templateID,String first,String keyword1,String keyword2,String keyword3,String keyword4,String keyword5 ,String remark,String openid){
		String result = "true";
		try {
			if(templateID==null){
				result = "error:templateID is null";
			}else if(openid==null){
				result = "error:openid is null";
			}
			String accessToken = WxUtils.GetAccessToken();
			JSONObject obj=new JSONObject();
			//
			obj.put("touser", openid);
			obj.put("template_id", templateID);
			obj.put("topcolor", "#FF0000");
//			System.out.println(first
//					+"|"+keyword1
//					+"|"+keyword2
//					+"|"+keyword3
//					+"|"+keyword4
//					+"|"+keyword5
//					+"|"+remark);
//			industryTemplateMessageSend
//					.setTemplate_id(templateID);// 暂时写死
//			industryTemplateMessageSend.setTouser(openid);
//			industryTemplateMessageSend.setUrl("");
//			industryTemplateMessageSend.setTopcolor("#FF0000");
			TemplateMessage data = new TemplateMessage();
			//first
			TemplateData firstT = new TemplateData();
			firstT.setColor("#173177");
			firstT.setValue(first);
			data.setFirst(firstT);

			//keyword1
			TemplateData keynote1 = new TemplateData();
			keynote1.setColor("#173177");
			keynote1.setValue(keyword1);
			data.setKeyword1(keynote1);

			//keyword2
			TemplateData keynote2 = new TemplateData();
			keynote2.setColor("#173177");
			keynote2.setValue(keyword2);
			data.setKeyword2(keynote2); 
			
			//keyword3
			TemplateData keynote3 = new TemplateData();
			keynote3.setColor("#173177");
			keynote3.setValue(keyword3);
			data.setKeyword3(keynote3);
			
			//keyword4
			TemplateData keynote4 = new TemplateData();
			keynote4.setColor("#173177");
			keynote4.setValue(keyword4);
			data.setKeyword4(keynote4);
			
			//keyword5
			TemplateData keynote5 = new TemplateData();
			keynote5.setColor("#173177");
			keynote5.setValue(keyword5);
			data.setKeyword5(keynote5);

			//remark
			TemplateData remarkT = new TemplateData();
			remarkT.setColor("#173177");
			remarkT.setValue(remark);
			data.setRemark(remarkT);
			
			obj.put("data",data);
			String reqUrl=String.format(
					"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",
					WxUtils.GetAccessToken());
			Map parameters=new HashMap();
			String jsonResultStr = HttpRequestProxy.doJsonPost(reqUrl, parameters,obj.toString());
		} catch (WexinReqException e) {
			result = e.getMessage();
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 系统服务验证码提醒
	 * @return
	 */
	@RequestMapping("system/access_token")
	@ResponseBody
	public String accessToken(){
		String accessToken = "";
		try {
			accessToken = WxUtils.GetAccessToken();
		} catch (WexinReqException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return accessToken;
	}
	@RequestMapping("common/getCard")
	public String getVipCard(Model model,HttpSession session){
		String openid = session.getAttribute("openid").toString();
		List<ActivateCard> alist = commonService.loadAccount(openid);
		session.setAttribute("ActivateCard", alist);
		return "common/getCard";
	}
}
